package com.shitou.shitouproduct.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitouproduct.config.RabbitMQConfit;
import com.shitou.shitouproduct.entity.CarouselEntity;
import com.shitou.shitouproduct.entity.HotSpuEntity;
import com.shitou.shitouproduct.entity.SpuInfoEntity;
import com.shitou.shitouproduct.service.CarouselService;
import com.shitou.shitouproduct.service.HotSpuService;
import com.shitou.shitouproduct.service.SpuInfoService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
@Component
public class ReleaseListener {

    @Autowired
    private SpuInfoService spuInfoService;
    @Resource
    private CarouselService carouselService;
    @Resource
    private HotSpuService hotSpuService;


    /**
     * 采用的是单个的，当然，也可以采用批量处理，，，，将elasticSearch 中的数据的状态设置为 0 不启用搜索
     * @param spuId
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfit.PRODUCT_RELEASE_QUEUE})
    public void releaseListener(Long spuId, Channel channel, Message message){
        SpuInfoEntity spuInfo = spuInfoService.getOne(new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
        spuInfoService.createSearchVo(spuInfo, true);
        Date date = new Date();
        // 修改数据库中的商品不可以进行展示
        setShow(spuId);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RRException(e.getMessage());
        }
    }


    /**
     * 设置轮播图和....修改数据库中的商品不可以进行展示
     * @param spuId
     */
    public void setShow(Long spuId){
        Date date = new Date();
        // 修改数据库中的商品不可以进行展示
        CarouselEntity carousel = carouselService.getOne(new QueryWrapper<CarouselEntity>().eq("spu_id", spuId));
        if ( carousel != null ){
            carousel.setStatus(1);
            carousel.setUpdateTime(date);
            carouselService.updateById(carousel);
        }

        HotSpuEntity hotSpu = hotSpuService.getOne(new QueryWrapper<HotSpuEntity>().eq("spu_id", spuId));
        if ( hotSpu != null ){
            hotSpu.setStatus(1);
            hotSpu.setUpdateTime(date);
            hotSpuService.updateById(hotSpu);
        }
    }
}
